# Why doesn't js file work in Google Chrome? 
#
# Clicking Serial number link will show ticket history:
# http://localhost/rt/webrt.cgi/webrt.cgi?serial_num=94710&display=History
#
# Clicking email link will enable user to reply to ticket requestor:
# http://localhost/rt/webrt.cgi/webrt.cgi?serial_num=94710&refresh_req=true&transaction=0&display=SetReply;
#
# http://localhost/rt/webrt.cgi/webrt.cgi/webrt.cgi?display=SetStatus&serial_num=94690

# Define a selector for choosing different Drop Downs -------------------------------------------
$statusSor = $('''
<select style="display: none">

</select>
''')

statusOptions = $('''
	<option value="open"> open </option>
	<option value="stall"> stalled </option>
	<option value="resolve"> resolved </option>
	<option value="kill" disabled='disabled'> dead </option>
''')

areaOptions = $('''
<option> None </option>
<option>Declined</option>
<option>Inquiries</option>
<option>Interview Requested</option>
<option>Placed - Admin</option>
<option>Placed - CC</option>
<option>Placed - PA</option>
<option>Placed - US/UT</option>
<option>Staff Requests</option>
''')

$editBtn = $('''
<div id='edit' style='position: absolute; display: table; text-align: right; color: RED; margin-top: -2px;'>
	<font style='font-size: 15px;'>
		[Edit]
	</font>
</div>
''')

$subjInput = $('''
<p style="display: none" id="genTextWrap">
	<input type="text" id="genTextArea"/>
	<br />
	<input type="submit" class="saveBtn" value="Save" />
	<input type="submit" class="cancelBtn" value="Cancel">
</p>
''')

# Tooltip definitions for Status
$statusTltip = $('''
<div id="statusTip" class="tooltip">
    change to a different status.
</div>
''')

# Tooltip definitions for Subject
$subjectTltip = $('''
<div id="subjectTip" class="tooltip">
    change to a different subject.
</div>
''')

# Tooltip definitions for Area
$areaTltip = $('''
<div id="areaTip" class="tooltip">
    change to a different area.
</div>
''')

# Tooltip definitions for Requestor email address
$emailTltip = $('''
<div id="emailTip" class="tooltip">
    change to a different email address.
</div>
''')

# Define useful CSS objects for debugging navigation
markCSS =
	'border-color': 'transparent'
	'border-style': 'solid'
unmarkCSS = 
	'border-color': 'none' 
	'border-style': 'none'
	
Deep = true

# Define a regex to match a ticket's serial number
serialNum = /serial_num=(\d+)/
rt_link = "/rt/webrt.cgi"

# Control flag that sets condition to displaying forms
ctrlFlag = false
hoverFlag = false

jQuery ($) ->

	# This function will serve a debugger for now because using alert method to quick debug is starting to
	# to get pretty annoying. Eventually this can be rewritten to be a tooltip implementation.
	#
	dbg = (msg) ->
	
		target = $('#msgDisplay > font')
		$('#msgDisplay').css('top' : window.pageYOffset)
		$('#msgDisplay').css('width' : window.innerWidth)
		target.delay(100).hide(0).text(msg).fadeIn(200)
	
		return
		
	# This function handles the cursor change for tooltip when the mouse moves
	changeTooltipPos = (event) ->
		tooltipX = event.pageX - 8;
		tooltipY = event.pageY + 8;
		$('div.tooltip').css({top: tooltipY, left: tooltipX});
		return
	
	# This function shows the tooltip when the mouse enters
	showTooltip = (event) ->
		colType = $(@).attr('id')	
		switch colType
			when 'status' then $tipText = $statusTltip.clone()
			when 'area' then $tipText = $areaTltip.clone()
			when 'subject' then $tipText = $subjectTltip.clone()
			else $tipText = $emailTltip.clone()
		$('div.tooltip').remove();
		$(this).append($tipText.clone());
		changeTooltipPos(event);
		return
	
	# This function hides the tooltip when the mouse leaves
	hideTooltip = (event) ->
		$('div.tooltip').remove();
		return

	$(document).on 'scroll ready', ->
		
		$('#msgDisplay').css('top' : window.pageYOffset)
		$('#msgDisplay').css('width' : window.innerWidth)		
		return

	# We will try to get webrt's main page from the server.
	#
	# >FIXME
	# We need to provide a load spinner.
	#
	$.get rt_link, (data, textStatus, jqXHR) ->

		# The data response is an HTML page.
		# We will use it to replace the starting HTML page.
		#
		# >FIXME
		# Result lacks a body tag
		#
		$('html').html data
		$('title').append('<link rel="stylesheet" href="tooltip.css" type="text/css" />')
		$('font[size="-1"] > table').before("<div id='msgDisplay' style='width: #{window.innerWidth};'>
		<font style='font-size: 14px; display: none;'></font>
		</div>")
		
		$('#msgDisplay').before('<div id="hiddenWrapper" style="display: none !important;"></div>')
		
		# $('#hiddenWrapper').before($pageCSS)
		
		# Every time the user clicks an anchor tag, we need to intercept it and
		# get the href ourself, otherwise, we will lose our Javascript file.
		$('html').on 'click', 'a', ->
			href = $(@).prop 'href'
			$.get href, (data) ->
				$('html').html data
			return false

		# The main page will be divided into several tables representing the major sections:
		#
		# * table header showing ticket properties
		# * table body listing tickets
		# * search form
		# * function bar
		# * footer
		#
		# >FIXME
		# Let's give an identifier to the sections, so we will locate them
		# easily.
		$('body >font >table >tbody >tr').prop 'id', 'header'
		$('body >font >table >tbody').prop 'id', 'tickets'
		$('body >form').prop 'id', 'search_form'
		$('body >table').prop 'id', 'function_bar'
		$('body >center').prop 'id', 'footer'

		# The main table will list one ticket per row with a core set of
		# properties, eg, priority, status, subject.  The major interactivity
		# of the main table will be that the user should be able to change the
		# value of an property by clicking it to enter an editing mode.

		# Let's adorn each table row with a class name and a serial number.
		$('font >table >tbody >tr').each ->
			$this = $(@)
			href = $('a', $this).attr 'href'
			if sn = (href.match serialNum)?[1]
				$this.addClass('ticket').attr 'id': sn
				$this.children('td:nth-child(3)').attr('id', 'status').addClass('dropDownCell')
				$this.children('td:nth-child(8)').attr('id', 'area').addClass('dropDownCell')
				$this.children('td:nth-child(5)').attr('id', 'subject').addClass('inputTypeCell')
				$this.children('td:nth-child(9)').attr('id', 'requestor').addClass('inputTypeCell')
							
		# >FIXME
		# Let's build a mapping from column position to column name by parsing
		# the table header.
		# colPosn = 
		# 	'status': 3
		
		# >FIXME
		# Let's get the list of possible status values and queue names by
		# parsing the search form.

		# >FIXME
		# Let's add tool tips for some columns, so that the user will know what
		# is possible if the column is clicked.  For example, if the user
		# hovers over the status column, the tip should say, 'change to a
		# different status', and so on.
		
		# Binding the events for the tooltip on the Status column
		$("td#status").bind({
			mousemove : changeTooltipPos,
			mouseenter : showTooltip,
			mouseleave: hideTooltip
			});	
		
		# Binding the events for the tooltip on the Subject column
		$("td#subject").bind({
			mousemove : changeTooltipPos,
			mouseenter : showTooltip,
			mouseleave: hideTooltip
			});	
			
		# Binding the events for the tooltip on the Area column
		$("td#area").bind({
			mousemove : changeTooltipPos,
			mouseenter : showTooltip,
			mouseleave: hideTooltip
			});	
			
		# Binding the events for the tooltip on the Requestor column	
		$("td#requestor").bind({
			mousemove : changeTooltipPos,
			mouseenter : showTooltip,
			mouseleave: hideTooltip
			});	

		$('tbody').on 'hover', 'td.inputTypeCell', ->
			
			if !$(@).children('#edit').length then hoverFlag = false
			
			if !hoverFlag & !ctrlFlag
				hoverFlag = true
				
				# Delay this so that the edit button isn't so flashy when mouse is traversing across
				# the table quickly
				cellPos = $(@).position()
				$(@).append($editBtn.clone())
				$(@).children('#edit').css('width' : $(@).innerWidth(),'top': cellPos.top, 'left' : cellPos.left)
				$(@).children('#edit').hide(0).delay(500).fadeIn(100)

			else
			
			$(@).children('#edit').children('font').mousemove ->
				$(@).css('text-decoration': 'underline' )
				return
				
			$(@).children('#edit').children('font').mouseleave ->
				$(@).css('text-decoration': 'none')
				return
			
			return

		$('tbody').on 'mouseleave', 'td.inputTypeCell', ->	
			if hoverFlag 
				$(@).children('#edit').remove()
				hoverFlag = false
			else
			return  

		$('tbody').on 'click', '#edit', ->
			
			hoverFlag = true
			ctrlWidth = $(@).parent().width()
			$host = $(@).parent()
			
			# Get the serial number of the current selected ticket to be operated
			# Since each tr has a ticket id, the parentNode id gives the serial number (or ticket)
			sn = $host.parent().attr('id')

			# Check to see if this control flag is marked. If True, then there is always a modifying control
			# somewhere on this page, so don't do anything. If false, then add the controls. 		
			if !ctrlFlag

				# Get the current value inside the td cell (for comparison)
				# (May not be necessary)
				currentValue = $host.children('font').text()

				# Make a copy of the current value inside the td cell and replace it
				# with the pre-generated text-field box
				$textVal = $host.children('font').clone Deep
				$host.empty().append $subjInput.clone()
				
				$host.css('width' : ctrlWidth)
		
				# Show the control (since it was set to display: none")
				$host.children().fadeIn(300)
		
				# Set the text inside the input box to currentValue and then focus the input box
				$host.children('P').children('INPUT[id="genTextArea"]').val(currentValue).focus()

				# Since we've added a control, set the control flag to true in order to restrict
				# any more controls to be added on to the webpage				
				ctrlFlag = true

			else

			# Event Hanlder for when the save button is clicked
			$host.children('P').on 'click', 'INPUT.saveBtn', ->
		
				# Get the subject in the previous inbox (which is the new subject to be saved)
				newValue = $(@).prevAll('INPUT').val()
				
				# If old subject and new subject are identical, don't send GET
				if newValue.toString() != $textVal.text().toString()
					dbg 'Waiting for server response..'
					$textVal.children('A').text("#{newValue} [..]")
				
				switch $(@).parent().parent().attr('id')
					when 'subject' 
						$.get rt_link, { serial_num : sn, do_req_subject : true, subject: newValue}, (data) ->
							exp = /Request .* subject has been changed to ".*"./
							$('#hiddenWrapper').html "<font> #{s = data.match(exp)[0].toString()} </font>"
							dbg s
							$textVal.text s.match(/"(.*?)"/)[1]
							return false
					when 'requestor'
						$.get rt_link, { serial_num : sn, do_req_user : true, recipient: newValue}, (data) ->
							$textVal.children('A').text newValue
							dbg 'Requestor has been changed'
							return false					
					else

				$(@).parent().replaceWith($textVal)
				ctrlFlag = false
				return false
	
			# Event Hanlder for when the cancel button is clicked
			$host.children('P').on 'click', 'INPUT.cancelBtn', ->
				$(@).parent().replaceWith($textVal)
				ctrlFlag = false
				return false
			return
		
		# Status: If the user mouse-clicks a status element, we will show a
		# selection of status values.  If the user clicks out, we will replace
		# it with the original element.
		$('tbody').on 'click', '.dropDownCell', ->
		
			ctrlWidth = $(@).width()
			ctrlHeight = $(@).height()
			columnType = $(@).attr('id')
			# Get the serial number of the current selected ticket to be operated
			# Since each tr has a ticket id, the parentNode id gives the serial number (or ticket)
			sn = this.parentNode.id
			
			# Check to see if this control flag is marked. If True, then there is always a modifying control
			# somewhere on this page, so don't do anything. If false, then add the controls. 
			if !ctrlFlag
			
				ctrlFlag = true
				
				# Get the currently displayed value of the status to determine what
				# selection should be shown on the dropdown selector			
				switch $(@).children('font').text()
					when 'resolved' then currentValue = 'resolve'
					when 'stalled' then currentValue = 'stall'
					else currentValue = $(@).children('font').text()
					
		
				switch columnType
					when 'status' then newOptions = statusOptions.clone()
					when 'area' 
						newOptions = areaOptions.clone()
						if currentValue.length != 1 then currentValue = currentValue.substr(0, currentValue.length - 1)
					else
				
				cellPos = $(@).position()
			
				# Since we've added a control, set the control flag to true in order to restrict
				# any more controls to be added on to the webpage
				$statusVal = $(@).children().clone Deep
				$(@).empty().append $statusSor.clone()
				
				$(@).children('SELECT').append newOptions
				
				#target = $(@).children('SELECT')
				#centerVer = cellPos.top + ctrlHeight / 2 - target.height() / 2
				#$(@).children('SELECT').css('position' : 'absolute', 'top' : centerVer)
				
				
				# Set the default option to what the current status is and then animate-show
				$(@).children('SELECT').children("OPTION:contains(#{currentValue})").attr("selected":"selected")

				$(@).children('SELECT').show 100
				
				# Focus the selector to control how to activate and deactivate the selector pulldown
				$(@).children('SELECT').focus()

				# When the selected option changes, perform HTTP_GET to server in order to set change
				$(@).change ->
					dbg 'Waiting for server response..'
					
					# Get what the user has just selected from the dropdown
					$statusVal.text("#{selected = $(@).children()[0].value.toString()} [..]")
					
					
					switch columnType
						when 'status'
							# Send HTTP_GET to parse the data
							$.get rt_link, { serial_num : sn, do_req_status : selected}, (data) ->
						
								exp = /Request #.* has been (opened|stalled|resolved)/
								$('#hiddenWrapper').html "<font> #{s = data.match(exp)[0].toString()} </font>"
								dbg s

								r = s.match(/(opened|resolved|stalled)/gi)[0]
								if r == 'opened' then r = 'open'
								$statusVal.text r
				
								return
						when 'area'
							setAreaLink = "#{rt_link}?serial_num=#{sn}&area=#{selected}&area=&do_req_area=true"
							$.get setAreaLink, (data) ->
								
								$statusVal.text "#{selected} "
								
								return
						else
					
					# After selection, lose the focus so the pulldown disappears
					this.childNodes[0].blur()
					
					
				$(@).on 'focusout', 'SELECT', ->
					$(@).replaceWith($statusVal)
					ctrlFlag = false
					return false
				
			else
						
			return 
		
		return # from get handler

	return
